import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';
import { AbstractControl, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';

@Component({
  selector: 'app-login-component',
  templateUrl: './login-component.component.html',
  styleUrls: ['./login-component.component.css']
})
export class LoginComponentComponent implements OnInit {
  //对应我们登录的表单
  myForm: FormGroup;

  //输入用户名的输入控件
  userName: AbstractControl;

  //输入密码的输入控件
  password: AbstractControl;

  baseUrl = 'http://127.0.0.1:8080/';
  name$: Observable<string>;
  

  constructor(private authService: AuthService, private fb: FormBuilder, private httpClient: HttpClient,private router: Router) {
    this.myForm = this.fb.group(
      {
        'userName': ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(20)])],
        'password': ['', Validators.compose([Validators.required, Validators.minLength(6), Validators.maxLength(16)])]
      }
    );


    this.userName = this.myForm.controls['userName'];
    this.password = this.myForm.controls['password'];
    this.name$ = this.userName.valueChanges;
    this.userName.valueChanges.subscribe(val => {
      console.log(val);
    })

  }

  ngOnInit(): void {
  }

  login() {
    this.authService.login();
  }

  onSubmit(value: any) {
    if (this.myForm.invalid) {
      alert('表单无效！');
      return;
    }
    this.httpClient.post(this.baseUrl + 'login', this.myForm.value).subscribe(
      (val: any) => {//val是服务器返回的值
        if (val.succ) {
          alert('登录成功！');
          this.authService.login();
          this.router.navigate(['/management']);
        } else {
          alert('登录失败！');
        }
      }
    );
  }
}
